<!-- 员工页面 -->
<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportToExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" width="200">
            <template #default="{row}">
              <img v-fixImg="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="staffPhoto" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column
            label="工号"
            sortable=""
            prop="workNumber"
          />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formEmployList" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 用插槽来接管 ,可以自己修改格式啥的 -->
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button v-if="checkPerm('delUser')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSettings.size" @current-change="currentChange" />
        </el-row>
      </el-card>
      <el-dialog :visible="isShowCode" title="二维码" @close="isShowCode=false">
        <el-row type="flex" justify="center">
          <canvas ref="code" />
        </el-row>
      </el-dialog>
      <!-- 新增员工组件 -->
      <addEmployee :show-dialog="showDialog" />
      <!-- 角色组件 -->
      <AssignRole ref="assignRole" :is-show-assign-role.sync="isShowAssignRole" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import EmployeeEnmu from '@/api/constant/employees'
import { getEmployeeList, delEmployee } from '@/api/employee'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import addEmployee from './components/addEmployee.vue'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
export default {
  components: { addEmployee, AssignRole },
  // 过滤器作用是接收不符合要求的字符串, 转换后返回符合要求的结果,替代源数据显示
  // filters: {
  //   formatDate(oldValue) {
  //     return oldValue.split('T')[0]
  //   }
  // },
  data() {
    return {
      isShowCode: false,
      pageSettings: {
        page: 1,
        size: 10
      },
      employeeList: [],
      total: 0,
      showDialog: false,
      isShowAssignRole: false
    }
  },
  async created() {
    this.getEmployeeList()
  },
  methods: {

    async assignRole(id) {
      await this.$refs.assignRole.getDetialById(id)
      this.isShowAssignRole = true
    },
    showCode(imgUrl) {
      this.isShowCode = true
      // 没有$nextTick会报错 , 页面更新 ,弹窗出现后,显示二维码
      this.$nextTick(() => {
        // QRCode 用法是调用一个叫toCanvas的函数
        // 传入二个必填属性 1.canvas dom节点 2.想要生成的字符串
        QRCode.toCanvas(this.$refs.code, imgUrl)
      })
    },
    objToarr(userObj, dict) {
      console.log('数据来源', userObj)
      const newUser = []
      for (const key in dict) {
        const enKey = dict[key]
        const value = userObj[enKey]
        // 处理时间和聘用形式的格式
        if (enKey === 'formOfEmployment') {
          // 处理聘用形式
          const obj = EmployeeEnmu.hireType.find(item => Number(item.id) === Number(value))
          newUser.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          newUser.push(formatDate(value))
        } else {
          newUser.push(value)
        }
      }
      console.log('最终转换格式', newUser)
      return newUser
    },
    async exportToExcel() {
      // 1.获取用户数据
      const { rows } = await getEmployeeList(this.pageSettings)
      console.log(95, rows)
      // 2.数据转换 按照顺序生成header和data
      // 准备顺序字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // Object.keys(对象)可以得出一个以对象的key组成的数组
      const header = Object.keys(dict)
      // 然后将用户对象映射插件需要的用户数组
      const data = rows.map(userObj => {
        // 遍历每一个用户对象,放入处理函数中
        // 同时传入字典 , 作为顺序的参考
        return this.objToarr(userObj, dict)
      })
      // 3.生成excel
      export_json_to_excel({
        header,
        data
      })
    },
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.pageSettings)
      console.log(total, rows)
      this.total = total
      this.employeeList = rows
    },
    // 分页改变时触发的函数
    currentChange(newPage) {
      this.pageSettings.page = newPage
      this.getEmployeeList()
    },
    // 格式化员工数据
    formEmployList(row, column, cell, index) {
      // 写法1:
      // return cell === 1 ? '正式' : '非正式'

      // 写法2:
      const obj = EmployeeEnmu.hireType.find(item => Number(item.id) === Number(cell))
      // 用可选链或者三元先判断一下obj存不存在
      return obj?.value
    },
    // 删除员工
    async delEmployee(id) {
      // 二次询问
      await this.$confirm('你确定要删除嘛?')
      // 发送请求
      await delEmployee(id)
      // 给出提示
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployeeList()
    }
  }
}

</script>
<style lang='scss' scoped>
.staffPhoto{
  width:180px;
  height:120px;
  object-fit:cover
}
</style>
